package com.wanglibao.woodtrade.woodtrade.ui.activity.adapter;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.NumberKeyListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.wanglibao.woodtrade.woodtrade.R;
import com.wanglibao.woodtrade.woodtrade.config.NetConfig;
import com.wanglibao.woodtrade.woodtrade.entity.GetGoodinfor;
import com.wanglibao.woodtrade.woodtrade.entity.MyGMOrderDetails;
import com.wanglibao.woodtrade.woodtrade.jsonrpc.JsonRPCAsyncTask;
import com.wanglibao.woodtrade.woodtrade.model.User;
import com.wanglibao.woodtrade.woodtrade.model.impl.UserImpl;
import com.wanglibao.woodtrade.woodtrade.ui.fragment.MyGMOrderFragment;
import com.wanglibao.woodtrade.woodtrade.util.ToastUtil;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by sony on 2016/5/27.
 * 个人中心中 购买fragment中的 listView 的适配器
 */
public class ItemLvMyGMOrderFragmentAdapter extends BaseAdapter {
    private List<MyGMOrderDetails.OrderListBean> mList = new ArrayList<>();

    private Context context;
    private LayoutInflater layoutInflater;
    MyGMOrderFragment mMyGMOrderFragment=new MyGMOrderFragment();
    public List<TextView> mTextViews_left_time=new ArrayList<>();
    GetGoodinfor mGoodinfor;
    double orderSize;
    Handler mHandler=new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if(msg.arg2!=2){
                if(msg.arg1== NetConfig.TaskId.get_good){
                  mGoodinfor=new Gson().fromJson(msg.obj.toString(),GetGoodinfor.class);
                    System.out.println(msg.obj.toString());
                    showDialog(mGoodinfor);
                }
                if(msg.arg1==NetConfig.TaskId.alter_order){
                    dialog.dismiss();
                    mMyGMOrderFragment.pageNumber=1;
                    mMyGMOrderFragment.NetWorking(mMyGMOrderFragment.zhuangtai);

                }
            }
            return false;
        }
    });

    public ItemLvMyGMOrderFragmentAdapter(Context context,List<MyGMOrderDetails.OrderListBean> list,MyGMOrderFragment myGMOrderFragment) {
        this.context = context;
        mList=list;
        mMyGMOrderFragment=myGMOrderFragment;
        this.layoutInflater = LayoutInflater.from(context);

    }

    public void setList(List<MyGMOrderDetails.OrderListBean> list) {
        mList = list;
        this.notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public MyGMOrderDetails.OrderListBean getItem(int position) {
        return mList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder=null;
        if (convertView == null) {
            viewHolder=new ViewHolder();
            convertView = layoutInflater.inflate(R.layout.item_lv_my_order_actvitiy1, null);
            viewHolder.tvStateItemLvMyOrder= (TextView) convertView.findViewById(R.id.tv_state_item_lv_my_order1);
            viewHolder.tvDianmingItemLvMyOrder= (TextView) convertView.findViewById(R.id.tv_dianming_item_lv_my_order1);
            viewHolder.imgvItemLvMyOrderActivity= (SimpleDraweeView) convertView.findViewById(R.id.imgv_item_lv_my_order_activity1);
            viewHolder.tvSpmItemLvMyOrder= (TextView) convertView.findViewById(R.id.tv_spm_item_lv_my_order1);
            viewHolder.tvGuigeItemLvMyOrder= (TextView) convertView.findViewById(R.id.tv_guige_item_lv_my_order1);
            viewHolder.tvShuliangItemLvMyOrder= (TextView) convertView.findViewById(R.id.tv_shuliang_item_lv_my_order1);
            viewHolder.tvTotalItemLvMyOrder= (TextView) convertView.findViewById(R.id.tv_total_item_lv_my_order1);
            viewHolder.tvDateLvMyOrder= (TextView) convertView.findViewById(R.id.tv_date_lv_my_order1);
            viewHolder.tvOrderNumberItemLvMyOrder= (TextView) convertView.findViewById(R.id.tv_orderNumber_item_lv_my_order1);
            viewHolder.tvShengYuDateLvMyOrder= (TextView) convertView.findViewById(R.id.tv_shengyu_date_lv_my_order1);
            viewHolder.imgbtEditItemLvMyOrder= (ImageButton) convertView.findViewById(R.id.imgbt_edit_item_lv_my_order1);
            convertView.setTag(viewHolder);
        }else {
            viewHolder= (ViewHolder) convertView.getTag();
            viewHolder.tvStateItemLvMyOrder.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                }
            });
            viewHolder.imgbtEditItemLvMyOrder.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            });
        }
        initializeViews((MyGMOrderDetails.OrderListBean) getItem(position), (ViewHolder) convertView.getTag(),position);
        return convertView;
    }
    String Status0="0";
    String Status1="1";
    String Status2="2";
    String Status3="3";
    private void initializeViews(final MyGMOrderDetails.OrderListBean entitiy, ViewHolder holder,int positon) {
        holder.tvDianmingItemLvMyOrder.setText(entitiy.getCompany());
        holder.imgvItemLvMyOrderActivity.setImageURI(Uri.parse(entitiy.getGoods_img()));
        holder.tvSpmItemLvMyOrder.setText(entitiy.getTitle());
        holder.tvGuigeItemLvMyOrder.setText("规格："+entitiy.getSize());
        holder.tvShuliangItemLvMyOrder.setText("数量："+entitiy.getGoods_num());
        holder.tvTotalItemLvMyOrder.setText("合计："+entitiy.getPay_fee()+"元");
        holder.tvDateLvMyOrder.setText("订单时间："+entitiy.getCreate_time().substring(0,10));
//        holder.tvShengYuDateLvMyOrder.setTag(positon);
        holder.tvOrderNumberItemLvMyOrder.setText("订单号："+entitiy.getOrder_sn());
        if(entitiy.getOrder_status().equals(Status0)){
            holder.tvStateItemLvMyOrder.setText("待确认");
            holder.imgbtEditItemLvMyOrder.setBackgroundResource(R.mipmap.ic_dingdan_edit);
            holder.tvShengYuDateLvMyOrder.setTag(positon);

            holder.imgbtEditItemLvMyOrder.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    User user = new UserImpl(context).getUser();
                    Order_id=entitiy.getOrder_id();
                    orderSize = Double.parseDouble(entitiy.getGoods_number());
                    //SERVER_wangliwei
                    JsonRPCAsyncTask jsonRPCAsyncTask = new JsonRPCAsyncTask((Activity) context, NetConfig.SERVER + NetConfig.TYPE_ORDER,
                            NetConfig.get_good,mHandler,"jsonObject",NetConfig.TaskId.get_good,
                            new Object[]{entitiy.getGoods_id(),user.token});
                    jsonRPCAsyncTask.execute(new Void[]{});

                }
            });
            holder.tvShengYuDateLvMyOrder.setText(convertTimeFormat(Long.parseLong(entitiy.getC_time())));
            mTextViews_left_time.add(holder.tvShengYuDateLvMyOrder);
        }else if(entitiy.getOrder_status().equals(Status1)){
            holder.tvStateItemLvMyOrder.setText("已确认");
            holder.imgbtEditItemLvMyOrder.setBackgroundResource(R.color.white);
            holder.tvShengYuDateLvMyOrder.setText(convertTimeFormat(Long.parseLong(entitiy.getC_time())));
            holder.tvShengYuDateLvMyOrder.setTag(positon);
            mTextViews_left_time.add(holder.tvShengYuDateLvMyOrder);
        }else if(entitiy.getOrder_status().equals(Status2)){
            holder.tvStateItemLvMyOrder.setText("已完成");
            holder.imgbtEditItemLvMyOrder.setBackgroundResource(R.color.white);
            holder.tvShengYuDateLvMyOrder.setText("");
        }else if(entitiy.getOrder_status().equals(Status3)){
            holder.tvStateItemLvMyOrder.setText("已失效");
            holder.imgbtEditItemLvMyOrder.setBackgroundResource(R.color.white);
            holder.tvShengYuDateLvMyOrder.setText("");
        }

    }

    public class ViewHolder {
        TextView tvDianmingItemLvMyOrder;
        SimpleDraweeView imgvItemLvMyOrderActivity;
        TextView tvSpmItemLvMyOrder;
        TextView tvGuigeItemLvMyOrder;
        TextView tvShuliangItemLvMyOrder;
        TextView tvTotalItemLvMyOrder;
        TextView tvDateLvMyOrder;
        TextView tvShengYuDateLvMyOrder;
        TextView tvOrderNumberItemLvMyOrder;
        TextView tvStateItemLvMyOrder;
        ImageButton imgbtEditItemLvMyOrder;

    }

    //把毫秒值转换成时.分.秒格式
    public String convertTimeFormat(long timeAll){
        long now=System.currentTimeMillis()-(timeAll*1000);
        int hour= (int) (timeAll/(1000*60*60));
        int timeleft1= (int) (timeAll%(1000*60*60));
        int minute= timeleft1/(1000*60);
        int timeleft2= (int) (timeAll%(1000*60));
        int second= timeleft2/1000;
        return "剩余时间："+hour+"时"+minute+"分"+second+"秒";
    }
    Dialog dialog;

    double orderNumber;
    double size;
    String Order_id;
    private void showDialog(final GetGoodinfor getGoodinfor) {
        size = Double.parseDouble(getGoodinfor.getGood().getUp_quantity());
        orderNumber=Double.parseDouble(getGoodinfor.getGood().getOrder_number());
        if (size == 0)size = 1;
        if (dialog != null && dialog.isShowing()) return;
        dialog = new Dialog(context, R.style.dialog_bgTransparent);
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
        dialog.getWindow().setContentView(R.layout.dialog_activity_commodity_sentorder);
        TextView tv_dialog_activity_commodity_type = (TextView) dialog.findViewById(R.id.tv_dialog_activity_commodity_type);
        tv_dialog_activity_commodity_type.setText(getGoodinfor.getGood().getCategory_name());
        TextView tv_dialog_activity_commodity_price = (TextView) dialog.findViewById(R.id.tv_dialog_activity_commodity_price);
        tv_dialog_activity_commodity_price.setText(getGoodinfor.getGood().getPrice()+"元/"+getGoodinfor.getGood().getUnit());
        TextView button = (TextView) dialog.findViewById(R.id.tv_dialog_activity_commodity_close);
        TextView tv_dialog_activity_commodity_quantity = (TextView) dialog.findViewById(R.id.tv_dialog_activity_commodity_quantity);
        tv_dialog_activity_commodity_quantity.setText("库存"+size+getGoodinfor.getGood().getUnit());
        final TextView tv_dialog_activity_commodity_count = (TextView) dialog.findViewById(R.id.tv_dialog_activity_commodity_count);
        double priceCount = Double.parseDouble(getGoodinfor.getGood().getPrice())*orderSize;
        DecimalFormat df = new DecimalFormat("######0.00");
        tv_dialog_activity_commodity_count.setText("总价:" + df.format(priceCount) + "元");
        Button btn_layout_commodity_sentorder_size_reduce = (Button) dialog.findViewById(R.id.btn_layout_commodity_sentorder_size_reduce);
        Button btn_layout_commodity_sentorder_size_plus = (Button) dialog.findViewById(R.id.btn_layout_commodity_sentorder_size_plus);
        final EditText edit_layout_commodity_sentorder_size_number = (EditText) dialog.findViewById(R.id.edit_layout_commodity_sentorder_size_number);

        edit_layout_commodity_sentorder_size_number.setKeyListener(new NumberKeyListener() {
            @Override
            protected char[] getAcceptedChars() {
                if ("吨".equals(getGoodinfor.getGood().getUnit())){
                    return new char[]{'0','1','2','3','4','5','6','7','8','9','.'};
                }else{
                    return new char[]{'0','1','2','3','4','5','6','7','8','9'};
                }
            }
            @Override
            public int getInputType() {
                return InputType.TYPE_CLASS_NUMBER;
            }
        });
        if (!"吨".equals(getGoodinfor.getGood().getUnit())){
            edit_layout_commodity_sentorder_size_number.setText((int)orderSize+"");
        }else{
            DecimalFormat df1 = new DecimalFormat("######0.0");
            edit_layout_commodity_sentorder_size_number.setText(df1.format(orderSize));
        }

        final double price = Double.parseDouble(getGoodinfor.getGood().getPrice());
        edit_layout_commodity_sentorder_size_number.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(s)){
//                    if (s.toString().indexOf(".") != s.toString().lastIndexOf(".") || // 判断 . 不能出现两次
//                            s.toString().indexOf(".") == 0 ||
//                            (s.toString().indexOf(".") > 0 && (s.toString().length()-1 - s.toString().indexOf(".")) > 1)||
//                            s.toString().length()-1 == s.toString().indexOf(".")){
//                        ToastUtil.createLongToast(context,"数据有误");
//                        return;
//                    }
                    double value = 0;
                    try {
                        value = Double.parseDouble(s.toString());
                        double priceCount = value * price;
                        DecimalFormat df = new DecimalFormat("######0.00");
                        tv_dialog_activity_commodity_count.setText("总价:" + df.format(priceCount) + "元");
                    }catch (NumberFormatException exception){}
                }
            }
        });
        btn_layout_commodity_sentorder_size_reduce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                double num = Double.parseDouble(edit_layout_commodity_sentorder_size_number.getText().toString());
                if (num > 0){
                    num--;
                }
                if (orderNumber > size){
                    ToastUtil.createLongToast(context,"库存不足");
                }else if (num < orderNumber){
                    ToastUtil.createLongToast(context,"不能少于起定量");
                    num++;
                }else{
                    double priceCount = num * price;
                    DecimalFormat df = new DecimalFormat("######0.00");
                    tv_dialog_activity_commodity_count.setText("总价:" + df.format(priceCount) + "元");

                    if (!"吨".equals(getGoodinfor.getGood().getUnit())){
                        edit_layout_commodity_sentorder_size_number.setText((int)num+"");
                    }else{
                        DecimalFormat df1 = new DecimalFormat("######0.0");
                        edit_layout_commodity_sentorder_size_number.setText(df1.format(num));
                    }
                }

            }
        });
        btn_layout_commodity_sentorder_size_plus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                double num = Double.parseDouble(edit_layout_commodity_sentorder_size_number.getText().toString());
                if (num >= 0){
                    num++;
                }
                if (orderNumber > size){
                    ToastUtil.createLongToast(context,"库存不足");
                }else if (num > size){
                    ToastUtil.createLongToast(context,"不能大于起库存");
                    num--;
                }else{
                    double priceCount = num * price;
                    DecimalFormat df = new DecimalFormat("######0.00");
                    tv_dialog_activity_commodity_count.setText("总价:" + df.format(priceCount) + "元");

                    if (!"吨".equals(getGoodinfor.getGood().getUnit())){
                        edit_layout_commodity_sentorder_size_number.setText((int)num+"");
                    }else{
                        DecimalFormat df1 = new DecimalFormat("######0.0");
                        edit_layout_commodity_sentorder_size_number.setText(df1.format(num));
                    }
                }

            }
        });
        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        TextView tv_dialog_activity_sentorder = (TextView) dialog.findViewById(R.id.tv_dialog_activity_sentorder);
        tv_dialog_activity_sentorder.setText("确认订单");
        tv_dialog_activity_sentorder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String num = edit_layout_commodity_sentorder_size_number.getText().toString();
                if (TextUtils.isEmpty(num)){
                    ToastUtil.createLongToast(context,"请填写购买数量");
                }else if(num.indexOf(".") > 0 && (num.length()-1 - num.indexOf(".")) > 1){
                    ToastUtil.createLongToast(context,"只能有一位小数");
                }else if (num.indexOf(".") != num.lastIndexOf(".") || // 判断 . 不能出现两次
                        num.indexOf(".") == 0 ||
                        (num.indexOf(".") > 0 && (num.length()-1 - num.indexOf(".")) > 1)||
                        num.length()-1 == num.indexOf(".")){
                    ToastUtil.createLongToast(context,"数量有误");
                }else if (orderNumber > size || Double.parseDouble(num) > size){
                    ToastUtil.createLongToast(context,"库存不足");
                }else if(Double.parseDouble(num) < orderNumber){
                    ToastUtil.createLongToast(context,"不能少于起定量");
                }else{
                    User user = new UserImpl(context).getUser();
                    //SERVER_wangliwei
                    JsonRPCAsyncTask jsonRPCAsyncTask = new JsonRPCAsyncTask((Activity) context, NetConfig.SERVER + NetConfig.TYPE_ORDER,
                            NetConfig.alter_order,mHandler,"jsonObject",NetConfig.TaskId.alter_order,
                            new Object[]{Order_id,user.token,edit_layout_commodity_sentorder_size_number.getText()});
                    jsonRPCAsyncTask.execute(new Void[]{});
                }
            }
        });
    }
}
